<template>
	<div class="app_container" v-loading="loading">
		<div class="content_chunk">
			<Info v-model="infoData" state="readonly" ref="editInfo"></Info>
		</div>
		<div class="content_chunk">
			<PriceAll
				v-model="infoData"
				state="readonly"
				ref="PriceAll"></PriceAll>
		</div>
		<div class="content_chunk">
			<Content v-model="infoData" state="readonly" type="edit"></Content>
		</div>
		<div class="handleBox">
			<el-button
				type=""
				@click="
					_toPage({
						path: '/finance/reimburs',
					})
				">
				取消
			</el-button>
			<el-button
				type="primary"
				v-show="state !== 'readonly'"
				:disabled="state && state == 'disabled'"
				@click="save">
				提交
			</el-button>
		</div>
	</div>
</template>

<script>
	import Info from '../chunk/editInfo.vue';
	import Content from '../chunk/chunk.vue';
	import PriceAll from '../chunk/priceAll.vue';
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import * as apis from '@/api/finance/reimburs/add/api.js';
	export default {
		name: 'EditReimburs',
		components: { FormItems, Info, Content, PriceAll },
		props: {
			state: {
				required: false,
				// default: "readonly",
			},
		},
		dicts: [
			'expense_use_type',
			'expense_use_type_car',
			'expense_use_type_pay',
			'expense_use_type_transport',
			'expense_use_type_registration',
			'expense_use_type_other',
			'expense_use_type_gps',
			'expense_business_cleancar',
			'expense_business_fuel',
			'expense_business_stopcar',
			'expense_business_road',
			'expense_business_car',
			'expense_business_pay',
			'expense_business_transport',
			'expense_business_registration',
			'expense_business_inspect',
			'expense_business_gps',
			'expense_business_other',
		],
		data() {
			return {
				loading: true,
				formList: [],

				infoData: {
					contractType: [],
					businessTypeVos: [],
				},
				checkedMenu: [],
				menu: [],
				dicts: {
					// 收款人类型
					payeeTypeList: [
						{
							label: '员工',
							value: '1',
						},
						{
							label: '司机',
							value: '2',
						},
						{
							label: '供应商',
							value: '3',
						},
					],
					contractTypeList: [
						{
							label: '短租',
							value: '1',
						},
						{
							label: '渠道',
							value: '2',
						},
						{
							label: '自营',
							value: '3',
						},
						{
							label: '代收代付',
							value: '4',
						},
					],
					needpayType: [
						{
							label: '是',
							value: '1',
						},
						{
							label: '否',
							value: '2',
						},
					],
					BusinessType: [],
				},
			};
		},
		provide() {
			return {};
		},
		computed: {
			id() {
				return this.$route?.query?.id;
			},
		},
		watch: {
			// menu: {
			// 	handler: function (val) {
			// 		console.log(val);
			// 	},
			// 	deep: true,
			// },
			// infoData: {
			//     handler: function (val) {
			//         console.log(val);
			//     },
			//     deep: true,
			// },
		},
		async mounted() {
			// console.log(this.getDicts("expense_business_1"));

			await this.getBusinessType();
			// this.getList();

			this.initInfo();
			this.menuBindDict();
			if (this.id) {
				this.initData();
			} else {
				this.dicts.BusinessType?.map(item =>
					this.checkedMenu.push(item.index),
				);
			}
		},
		methods: {
			getDateDuration(startTime, endTime) {
				let result = '-';
				let start = this.$dayjs(startTime);
				let end = this.$dayjs(endTime);
				let duration = this.$dayjs.duration(end.diff(start));
				let H_all = duration.as('hours');
				let D = parseInt(H_all / 24);
				let H = (H_all % 24).toFixed(1)?.split('.');
				if (D == 0) {
					result = `${H} 小时`;
				} else if ((H?.[0] == 0 && H?.[1] == 0) || (!H[0] && !H[1])) {
					result = `${D} 天`;
				} else if (H?.[1] == 0) {
					result = `${D} 天 ${H[0]} 小时`;
				} else {
					result = `${D} 天 ${H[0]}.${H[1]} 小时`;
				}
				return result;
			},
			menuBindDict() {
				this.dicts.BusinessType.map(item => {
					let child = this.menu.find(e => e.title === item.value);
					if (child) {
						this.$set(child, 'dictType', item.dictType);
						this.$set(child, 'value', item.index);
					}
				});
			},
			async getBusinessType() {
				return new Promise((resolve, reject) => {
					this.loading = true;
					let params = {};
					apis?.BusinessType(params)
						.then(res => {
							this.dicts.BusinessType = res.data;
						})
						.catch(err => {
							reject();
						})
						.finally(() => {
							this.loading = false;
							resolve();
						});
				});
			},
			initData() {
				this.loading = true;
				apis?.Details(this.$route.query.id)
					.then(res => {
						if (res.code == 200) {
							let data = res.data;
							// data?.businessTypeVos.map((item) => {
							//     this.checkedMenu.push(item.businessType * 1);
							// });
							// this.menu.map((item) => {
							//     let vos = data?.businessTypeVos?.find(
							//         (e) => e.businessType == item.value
							//     );
							//     if (!!vos) {
							//         item.data = vos;
							//         item.data.list = vos?.businessInfoVos ?? [];
							//         Reflect.deleteProperty(
							//             item.data,
							//             "businessInfoVos"
							//         );
							//     }
							// });

							this.infoData = data;
							// this.infoData.contractType =
							//     this.infoData?.contractType?.split?.(",");
							// Reflect.deleteProperty(
							//     this.infoData,
							//     "businessInfoGroupVos"
							// );
							// Reflect.deleteProperty(
							//     this.infoData,
							//     "businessTypeVos"
							// );
						}
					})
					.finally(() => {
						this.loading = false;
					});
			},

			initInfo() {
				this.formList = [
					{
						label: '所属公司',
						type: 'select_dialog',
						propLabel: 'companyName',
						prop: 'companyId',
						select_dialog: {
							type: 'company',
							title: '请选择公司',
						},
						rules: [
							{
								required: true,
								message: '请选择公司',
								trigger: 'change',
							},
						],
						rulesProp: 'companyId',
						cb: (res, row) => {
							this.$set(row, 'companyName', res.companyName);
							this.$set(row, 'companyId', res.companyId);
							this.menu.map(item => {
								item?.data?.list?.map(ele => {
									this.$emit(
										ele,
										'companyName',
										res.companyName,
									);
									this.$set(ele, 'companyId', res.companyId);
								});
							});
						},
					},
					{
						label: '使用日期',
						type: 'datePicker',
						prop: 'payTime',
						clounmMinWidth: '200px',
						datePickerType: 'month',
						valueFormat: 'yyyy-MM',
					},
					{
						label: '收款人类型',
						type: 'radioGroup',
						prop: 'payeeType',
						radioGroupList: this.dicts.payeeTypeList,
					},
					{
						label: '合同类型',
						type: 'checkboxGroup',
						prop: 'contractType',
						checkboxGroupList: this.dicts.contractTypeList,
					},
					{
						label: '选择收款人',
						type: 'select',
						prop: 'payeeUserId',
						selectList: [],
					},
					{
						label: '收款人名称',
						type: 'input',
						prop: 'payeeUserName',
					},
					{
						label: '收款卡号',
						type: 'input',
						prop: 'paymentCardId',
					},
					{
						label: '收款账户名称',
						type: 'input',
						prop: 'paymentAccount',
					},
				];
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
			async save() {
				let pass = await this.valid();
				if (!pass) {
					this.scrollToError();
					return;
				}

				let empty = true;
				if (this.infoData?.businessTypeVos.length == 0) {
					empty = true;
				} else {
					businessTypeVos: for (
						let index = 0;
						index < this.infoData?.businessTypeVos.length;
						index++
					) {
						const element = this.infoData?.businessTypeVos[index];
						if (element.businessInfoVos?.length !== 0) {
							empty = false;
							break businessTypeVos;
						}
					}
				}
				if (empty) {
					this.$message.error('请添加报销信息');
					return;
				}

				// for (let index = 0; index < components.length; index++) {
				//     const element = components[index];
				//     let pass = await element?.validate();
				//     let index = this.infoData.businessTypeVos?.findIndex(
				//         (i) =>
				//             i.businessType * 1 ==
				//             element?.infoData?.businessType * 1
				//     );
				//     if (index !== -1) {
				//         result = result && pass;
				//     }
				//     // if (
				//     //     this.checkedMenu.includes(
				//     //         element?.infoData?.businessType * 1
				//     //     )
				//     // ) {
				//     //     result = result && pass;
				//     // }
				// }
				let infoData_copy = this._.cloneDeep(this.infoData);
				// let menu_copy = this._.cloneDeep(this.menu);
				let params = Object.assign({}, infoData_copy, {
					businessTypeMap: {},
					businessInfoMap: {},
				});
				// menu_copy = menu_copy.filter((item) =>
				//     this.checkedMenu.includes(item.value)
				// );
				let emptyPrice = true;
				infoData_copy.businessTypeVos?.map(item => {
					params.businessTypeMap[item.businessType] ??= {};
					params.businessInfoMap[item.businessType] ??= [];
					// item.data.businessInfoVos ??= [];
					if (item?.invoiceUploadType == 2) {
						this.resetInvoice(item);
					}
					Object.keys(item).map(key => {
						if (key == 'businessInfoVos') {
							if (
								item?.businessInfoVos &&
								item?.businessInfoVos?.length > 0
							) {
								params.businessInfoMap[item.businessType] =
									item?.businessInfoVos;
							}
						}
					});
					let price = item.businessInfoVos?.reduce((prev, next) => {
						if (
							Number.isFinite(Number(next.money)) ||
							Number.isFinite(Number(next.monthMoney))
						) {
							return this.numberAdd(
								prev,
								this.notEmpty(next.money)
									? next.money
									: next.monthMoney,
							);
						}
					}, 0);
					if (price !== 0) {
						emptyPrice = false;
					}
					// delete item.data.list;
					// if (Object.keys(item.data).length > 0) {
					params.businessTypeMap[item.businessType] = {
						...item,
						businessType: item.businessType,
						expenseNum: item.businessInfoVos?.length ?? 0,
						expenseMoney: price,
					};
					// }

					Reflect.deleteProperty(
						params.businessTypeMap[item.businessType],
						'businessInfoVos',
					);
				});
				params.contractType = params.contractType.join(',');
				// if (this.id) params.id = this.id;
				// console.log(this.menu);
				// console.log(result);
				Reflect.deleteProperty(params, 'businessInfoGroupVos');
				Reflect.deleteProperty(params, 'businessTypeVos');

				if (emptyPrice) {
					this.$message.error('报销金额不能为0');
					return;
				}
				if (pass) {
					this.$modal.loading('正在保存...');
					let method = this.$route.query.id ? apis?.Edit : apis?.Edit;
					method?.(params)
						.then(res => {
							if (res.code == 200) {
								this.$message.success('保存成功');
								const obj = this.$route;
								this.$tab.closeOpenPage(obj).then(() => {
									this.$router.push({
										path: '/finance/reimburs',
									});
								});
							}
						})
						.finally(res => {
							this.$modal.closeLoading();
						});
				} else {
					this.scrollToError();
					this.$message({
						type: 'error',
						message: '请先完善表单！',
					});
					return;
				}
			},
			resetInvoice(item) {
				item.invoiceOssId ??= '';
				item.otherOssId ??= '';
				item.invoiceType ??= '';
				item.invoiceMoney ??= '';
				item.taxMoney ??= '';
				item.taxRate ??= '';
			},
			// 设置chunk需要的数据
			initItemData(key, data = {}) {
				let item = this.menu.find(item => {
					return item.value == key;
				});
				if (!item) return;
				item.data = data;
			},
		},
	};
</script>

<style scoped lang="scss">
	.app_container {
		background-color: #f0f2f5;
		.container {
			border-radius: 10px;
			background-color: #fff;
			margin: 20px;
			padding: 20px;
			.container_title {
				margin-bottom: 30px;
				padding: 0px 0 20px 0;
				border-bottom: 1px solid #191919;
				font-size: 16px;
				color: #333;
				font-weight: 600;
			}
			.container_content {
				// padding: 20px;
			}
		}
	}
	.chunk_nav {
		background-color: #fff;
		// padding: 20px 0;
		.nav_item {
			padding-bottom: 30px;
			display: flex;
			.label {
				min-width: 0;
				width: 250px;
				text-align: right;
				padding-right: 25px;
				box-sizing: border-box;
			}
			.content {
				flex: 1;
				min-width: 0;
				padding-right: 50px;
				.menu {
					width: 100%;
					display: grid;
					grid-template-columns: repeat(6, minmax(0, 1fr));
					gap: 5px 0;
				}
			}
		}
	}
	.chunk_contentBox {
		background-color: #fff;
		// padding: 25px;
		.chunk {
			margin-bottom: 50px;
		}
	}
	.remakeBox {
		display: flex;
		margin-bottom: 20px;
		.label {
			font-size: 14px;
			margin-right: 15px;
		}
		.content {
			width: 370px;
		}
	}
	.handleBox {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		margin: 20px;
		padding: 15px 20px;
		background: #ffffff;
		border-radius: 8px;
	}
	::v-deep .gridBox {
		padding-top: 0;
	}
	.component-fade-enter, .component-fade-leave-to
/* .component-fade-leave-active for below version 2.1.8 */ {
		transform: translateX(100px);
		opacity: 0;
	}

	.component-fade-enter-active,
	.component-fade-leave-active {
		transition: all 0.8s;
	}
	.content_chunk {
		margin: 20px;
	}
</style>
